import { AbstractControl, FormControl } from '@angular/forms';

export class CustValidators {

  static maxByteLength(maxLength: Number) {
    return (control: FormControl): { [key: string]: any } => {
      if(!control.value) return null
      if(CustValidators.getBytesLength(control.value) > maxLength){
        return { maxByteLength: { maxByteLength: maxLength, actualValue: control.value } }
      }else{
        return null
      }
    }
  }

  static telPhoneValidate() {
    return (control: FormControl): { [key: string]: any } => {
      if(!control.value) return null
      if(/^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(control.value) || /^[0-9]{8}$/.test(control.value)){
        return null
      }else{
        return { telPhoneValidate: { error: '联系方式不正确' } }
      }
    }
  }



  

  private static getBytesLength(str: string) {
    var totalLength = 0;
    var charCode;
    for (var i = 0; i < str.length; i++) {
      charCode = str.charCodeAt(i);
      // if (charCode < 0x007f) {
      //   totalLength++;
      // } else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) {
      //   totalLength += 2;
      // } else if ((0x0800 <= charCode) && (charCode <= 0xffff)) {
      //   totalLength += 3;
      // } else {
      //   totalLength += 4;
      // }
      if (charCode < 0x007f) {
        totalLength++;
      } else {
        totalLength += 2;
      }
    }
    return totalLength;
  }

  // 示例 
  // static Limit(limit: number) {
  //   return (control: FormControl): { [key: string]: any } => {
  //     let val = Number(control.value);
  //     if (val != NaN && val > limit) {
  //       return { "limit": { "limit": limit, "actualValue": val } };
  //     } else {
  //       return null;
  //     }
  //   }
  // }

}
